from django.shortcuts import render,redirect
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from hashlib import sha1
from df_user.models import *
from df_user.islogin import islogin
from df_goods.models import *
from df_order.models import *
from df_cart.models import *
from django.core.paginator import Paginator


# Create your views here.

def register(request):
    context = {'title':'注册'}
    return render(request, 'df_user/register.html', context)

def login(request):
    uname = request.COOKIES.get('uname', '')
    context = {'title':'登录', 'error_name':0, 'error_pwd': 0, 'uname':uname}
    return render(request, 'df_user/login.html', context)

def register_handle(request):
    # 用户注册输入的信息
    post = request.POST
    uname = post.get('user_name')
    upwd = post.get('pwd')
    ucpwd = post.get('cpwd')
    email = post.get('email')

    if upwd != ucpwd:
        return redirect('/user/register')

    # 对密码原文进行sha1的加密
    s1 = sha1()
    s1.update(upwd.encode())
    upwd2 = s1.hexdigest()

    # 创建模板对象 并填入数据 然后写入数据库中
    user = UserInfo()
    user.uname = uname
    user.upwd = upwd2
    user.uemail = email
    user.save()

    # 跳转到登录页面
    return redirect('/user/login')

def register_exist(request):
    # 接收用户输入的get参数uname
    get = request.GET
    uname = get.get('uname')

    # 在数据库中查询用户是否存在
    count = UserInfo.objects.filter(uname = uname).count()
    return JsonResponse({'count':count})


def login_handle(request):
    # 接收用户输入的参数
    post = request.POST
    uname = post.get('username')
    upwd = post.get('pwd')
    jizhu = post.get('jizhu')

    # 根据用户名和密码查询数据库
    users = UserInfo.objects.filter(uname=uname)
    if len(users) > 0:
        # 用户存在
        # 对密码原文进行sha1加密
        s1 = sha1()
        s1.update(upwd.encode())
        upwd2 = s1.hexdigest()

        # 与数据库中的密码进行比较
        if upwd2 == users[0].upwd:

            # 从cookie中提取之前保存好的路径
            url = request.COOKIES.get('url', '/user/info')
            # 登录成功
            red = HttpResponseRedirect(url)
            if jizhu:
                red.set_cookie('uname', uname)  # 记住用户名
            else:
                red.set_cookie('uname', '')  # 没有记住用户名
            request.session['user_id'] = users[0].id
            request.session['user_name'] = uname

            return red
        else:
            print('密码不正确')
            # 登录失败
            context = {'title': '登录', 'error_name':0, 'error_pwd':1,
                       'uname':uname, 'upwd':upwd}
            return render(request, 'df_user/login.html', context)
    else:
        print('用户不存在')
        # 用户不存在
        context = {'title': '登录', 'error_name':1, 'error_pwd':0,
                   'uname': uname, 'upwd': upwd}
        return render(request, 'df_user/login.html', context)

@islogin
def info(request):
    # 读取数据库中的用户信息
    user = UserInfo.objects.get(id=request.session['user_id'])
    user_name = user.uname
    user_address = user.uaddress
    # 隐藏电话号码中间4个字符
    phone = user.uphone[:3] + '****' + user.uphone[-4:]
    # 从cookies中读取最近浏览的信息
    goods_ids = request.COOKIES.get('goods_ids')
    # 判断cookies中的最近浏览商品序列是否为空
    if goods_ids and goods_ids != '':
        goods_ids = goods_ids.split(',')
    else:
        goods_ids = []
    # print(goods_ids)
    # 注意goods_ids只保存id 我们在模板中需要名称、价格、单价、图片地址等 所以需要传递商品对象的列表
    goods_list = []
    for id in goods_ids:
        # 遍历goods_ids 根据id找到商品对象 把商品对象添加到goods_list列表中
        goods = GoodsInfo.objects.get(id=id)
        goods_list.append(goods)
    context = {'title': '用户中心',
                'user_name': user_name,
               'user_address': user_address,
               'user_phone': phone,
               'info': 1,
               'user_center': 1,
               'goods_list': goods_list,
               }
    return render(request, 'df_user/user_center_info.html', context)

@islogin
def order(request,pageid):
    user = UserInfo.objects.get(id=request.session['user_id'])

    uid = user.id
    # order = OrderInfo.objects.filter(user_id = uid).order_by('-order_id')[:1]
    order = OrderInfo.objects.filter(user_id = uid).order_by('-o_time')
    # print(order)
    # list = []
    if (order):
        for i in order:
            orderid = i.order_id
            goodsdetal = Order_GoodsInfo.objects.filter(order_id=orderid)
            for gs in goodsdetal:
                gs.sub = float(gs.count) * float(gs.price)
            i.goodsdetal= goodsdetal

            # list.append(goodsdetal)

    # print('商品订单：',list)
    #分页
    paginator = Paginator(order, 2)
    pageid = int(pageid)
    goodList = paginator.page(pageid)
    pindexlist = paginator.page_range


    context = {'title':'用户中心',
               'order': 1,
               'user_center': 1,
               'orderlist':goodList,
               'pindexlist': pindexlist,
               'pageid':pageid
               # 'goodsdetal':list,
               # 'count':count,
               # 'subtotal':g.subtotal
               }
    return render(request, 'df_user/user_center_order.html', context)

@islogin
def site(request):
    # 从数据库中获取用户相关信息
    user = UserInfo.objects.get(id=request.session['user_id'])

    if request.method == 'POST':
        post = request.POST
        user.ushou = post.get('ushou')
        user.uaddress = post.get('uaddress')
        user.uyoubian = post.get('uyoubian')
        user.uphone = post.get('uphone')
        user.save()
    # 隐藏电话号码中间4个字符
    phone = user.uphone[:3] + '****' + user.uphone[-4:]

    context = {'title': '用户中心',
               'site': 1,
               'ushou': user.ushou,
               'uaddress': user.uaddress,
               'uyoubian': user.uyoubian,
               'uphone': phone,
               'user_center': 1
               }
    return render(request, 'df_user/user_center_site.html', context)

def logout(request):
    request.session.flush() # 清空session缓存
    return HttpResponseRedirect('/user/login')